import React, { useState, memo, useEffect, useRef } from 'react';
import { Row, Col, message, Switch, Button, Image } from 'tdesign-react';
import { createBlogApi, getArtClassListApi, getListApi,putBlogApi } from 'api/operation/blog';
import proxy from 'configs/host';
import { uploadFileApi } from 'api/common';
import classnames from 'classnames';
import CommonStyle from 'styles/common.module.less';
import useLoading from 'hooks/useLoading';
import { createColumns } from 'utils/tableUtils';
import SakuraSearchForm from 'components/SakuraSearchForm';
import SakuraModal from 'components/SakuraModal';
import { IModalRef } from 'components/SakuraModal/types';
import { BLOG_CATEGORY_MAP, getBLOG_CATEGORY_MAP, handleUpdateStatus, PARRENT_TYPE_OPTIONS, type_MAP } from './consts';
import IppeakTable from 'components/IppeakTable';
import StatusSwitch from 'components/StatusSwitch';
import IppeakImage from 'components/IppeakImage';
import SakuraDrawer from 'components/SakuraDrawer';
import DetailDrawer from './detail';

export const SelectTable = () => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<(string | number)[]>([0, 1]);
  const [visible, setVisible] = useState(false);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detailItem, setDetailItem] = useState<any>(null);
  const { loading, setLoading } = useLoading(false);
  const [opType, setOpType] = useState<'Add' | 'Edit'>('Add');
  const [editingItem, setEditingItem] = useState<any>(null);
  const modalRef = useRef<IModalRef | any>(null);
  const [artClassList, setArtClassList] = useState<any[]>([]);
  const [ARTCLASSMAP, setARTCLASSMAP] = useState<any>([]);

  // 获取BLOG_ARTCLASSMAP的函数
  const getBLOG_ARTCLASSMAP = () => {
    return localStorage.getItem('BLOG_ARTCLASSMAP') ? JSON.parse(localStorage.getItem('BLOG_ARTCLASSMAP') || '') : [];
  };
  const initData = {
    status: 1,
    pack_type: '1',
    order_type: 9,
    email: '',
  };
  const fields: any[] = [
    { label: '邮箱', name: 'email', type: 'input', required: true },
    {
      label: '套餐类型',
      name: 'pack_type',
      type: 'select',
      options: [{ label: '流量', value: 1 }],
      required: true,
      disabled: true,
    },
    { label: '流量', name: 'flow', type: 'input', required: true, appendSuffix: 'G' },
    { label: '时效', name: 'day', type: 'input', required: true, appendSuffix: '天' },
    {
      label: '订单类型',
      name: 'order_type',
      type: 'select',
      options: [],
      disabled: true,
      help: '试用订单仅对没有GB套餐的用户生效；',
    },
    { label: '备注', name: 'remarks', type: 'textarea', props: { autosize: { minRows: 3, maxRows: 10 } } },
  ];
  const columns = createColumns([
    {
      label: 'ID',
      key: 'id',
    },
    {
      label: '分类-中文',
      key: 'art_class',
      width: '200',
      render: ({ row }: any) => {
        const BLOG_ARTCLASSMAP = localStorage.getItem('BLOG_ARTCLASSMAP') ? JSON.parse(localStorage.getItem('BLOG_ARTCLASSMAP') || '') : [];
        const categoryLabel = BLOG_ARTCLASSMAP.find((item: any) => item.value === row.art_class)?.label || '-';
        return <span>{categoryLabel}</span>;
      },  
    },
    {
      label: '标题-中文',
      key: 'title',
      width: '250',
    },
    {
      label: '配图',
      key: 'cover',
      width: '200',
      render: ({ row }: any) => (
          row.cover ? (
            <IppeakImage 
              src={row.cover.startsWith('http') ? row.cover : `${proxy[(import.meta.env.MODE || 'development') as keyof typeof proxy].API}${row.cover}`}
              width={200}
              height={100}
              fit="cover"
              shape="round"
              alt="配图"
            />
          ) : (
            <span>-</span>
          )
      ),
    },
   
    {
      label: '状态',
      key: 'region',
      render: ({ row }: any) => (
        <StatusSwitch
          value={row.status===0?true:false}
          loading={updatingRows.has(row.id)}
          onChange={(newValue) => handleUpdateStatus(newValue, row, setUpdatingRows, setTable)}
          row={row}
          activeText="启用"
          inactiveText="禁用"
        />
      ),
    },
    {
      label: '操作人',
      key: 'creator',
      width: '150',
    },
    {
      label: '操作时间',
      key:'created',
      width: '150',
      type:'date'
    },
    {
      label: '操作',
      key: 'op',
      width: '150',
              render: ({ row }: any) => (
         <>
         <Button  theme='primary' variant='text' onClick={() => handleDetailClick(row)}>
           详情
          </Button>
         <Button  theme='primary' variant='text' onClick={() => handleEditClick(row)}>
         编辑
       </Button></>
      ),
    },
  ]);
  const [table, setTable] = useState({
    list: [],
    total: 0,
    current: 1,
    pageSize: 10,
  });
  const [query, setQuery] = useState({
    page: 1,
    page_size: 10,
  });
  const [updatingRows, setUpdatingRows] = useState<Set<string | number>>(new Set());
  const drawerRef = useRef<any>(null);
  const formFields: any[] = [
    {
      label:'分类',
      name:'art_class',
      type:'select',
      options: getBLOG_ARTCLASSMAP(),
      colWrap: {
        colSpan: 1.5,
        labelWidth: 60,
      },
    },
    {
      label: '状态',
      name: 'status',
      type: 'select',
      options: [{ label: '启用', value: 1 }, { label: '禁用', value: 2 }],
      colWrap: {
        colSpan: 1.5,
        labelWidth: 50,
      },
    },
  
  ];
  const { list, total, current, pageSize } = table;
  const fetchUserList = async (params?: any) => {
    setLoading(true);
    try {
      const res: any = await getListApi({ ...params, ...query });
      setLoading(false);
      setTable((pre: any) => ({
        ...pre,
        list: res.results.map((item: any)=>({...item,art_class_en:item.art_class})) || [],
        total: res.total || 0,
        pageSize: res.page_size || 10,
        current: res.page || 1,
      }));
    } catch (err) {
      console.log(err, 'err');
    }
  };
  function onSelectChange(value: (string | number)[]) {
    setSelectedRowKeys(value);
  }

  const handleAddClick = () => {
    setEditingItem(null);
    setOpType('Add');
    setDrawerVisible(true);
  };

  const handleEditClick = (row: any) => {
    const editData = { ...row };
    if (editData.cover && typeof editData.cover === 'string') {
    }
    
    setEditingItem(editData);
    setOpType('Edit');
    setDrawerVisible(true);
  };

  const handleDetailClick = (row: any) => {
    setDetailItem(row);
    setDetailVisible(true);
  };

  const handleDrawerSubmit = async (type: string, values: any, cb: () => void) => {
    try {
      const uploadedImageUrl = drawerRef.current?.getUploadedImageUrl();
      const sanitizedUploadedUrl = typeof uploadedImageUrl === 'string'
        ? (() => {
            const idx = uploadedImageUrl.indexOf('static');
            return idx > 0 ? '/'+uploadedImageUrl.slice(idx) : uploadedImageUrl;
          })()
        : uploadedImageUrl;
      const formData = {
        art_class: values.art_class || '',
        art_class_en: values.art_class_en || '',
        title: values.title || '', 
        en_title: values.en_title || '',
        keyword: values.keyword || '', 
        description: values.description || '', 
        cover: sanitizedUploadedUrl || values.cover || '',
        content: values.content || '', 
        en_content: values.en_content || '',
        status: values.status !== undefined && values.status !== null ? Number(values.status) : undefined, 
        auth: values.auth || '', 
      };
      let res;
      if (type === 'Add') {
        res = await createBlogApi(formData);
      } else if (type === 'Edit') {
        const editId = editingItem?.id;
        if (!editId) {
          throw new Error('编辑时缺少ID');
        }
        const editFormData = {
          ...formData,
          id: editId
        };
        res = await putBlogApi(editFormData);
      } else {
        throw new Error('未知的操作类型');
      }
      
      message.success(`${type === 'Add' ? '新增' : '编辑'}成功`);
      cb();
      setDrawerVisible(false);
      fetchUserList();
    } catch (err: any) {
      console.error('提交失败:', err);
      message.error('操作失败');
    }
  };

  const handleDrawerClose = () => {
    setDrawerVisible(false);
    setEditingItem(null);
  };

  // SakuraDrawer表单字段配置 - 使用DrawerForm
  const drawerFormFields = [
    {
      name: 'art_class',
      label: '分类-中文',
      type: 'select' as const,
      options: getBLOG_ARTCLASSMAP(),
      required: true,
      colSpan: 6,
      onChange: (value: any, form: any) => {
        // 当选择中文分类时，自动设置英文分类；当清空时，同步清空英文分类
        if (!value) {
          form?.setFieldsValue({ art_class_en: undefined });
          return;
        }
        // 根据选择的中文分类值，找到对应的英文分类
        const selectedCategory = getBLOG_ARTCLASSMAP().find((item: any) => item.value === value);
        if (selectedCategory && form) {
          // 通过表单实例设置英文分类字段的值（value 相同）
          form.setFieldsValue({ art_class_en: value });
        }
      }
    },
    {
      name: 'art_class_en',
      label: '分类-英文',
      type: 'select' as const,
      options: getBLOG_ARTCLASSMAP().map((item:any)=>({label:item.labelEn,value:item.value})),
      disabled: true,
      required: true,
      colSpan: 6,
    },
    {
      name: 'title',
      label: '标题-中文',
      required: true,
      type: 'input' as const,
      colSpan: 12,
    },
    {
      name: 'en_title',
      label: '标题-英文',
      required: true,
      type: 'input' as const,
      colSpan: 12,
    },
   
    {
      name: 'keyword',
      label: '关键词',
      required: true,
      type: 'textarea' as const,
      colSpan: 12,
      textareaProps: {
        maxLength: 60,
        tips: '关键词长度不能超过60个字符',
      },
      formItemStyle: {
        marginBottom:'5px'
      },
    },
    {
      name: 'description',
      label: '描述',
      required: true,
      type: 'textarea' as const,
      props: { autosize: { minRows: 3, maxRows: 6 } },
      colSpan: 12,
      textareaProps: {
        maxLength: 160,
        tips: '描述长度不能超过160个字符',
      },
      formItemStyle: {
        marginBottom:'5px'
      },
    },
    {
      name: 'cover',
      label: '配图',
      required: true,
      type: 'upload' as const,
      colSpan: 6,
      props: {
        accept: 'image/*',
        max: 1,
        autoUpload: true,
        placeholder: '请选择图片',
        showUploadProgress: false, // 不显示上传进度
        theme: 'image' // 确保使用图片上传主题
      }
    },
    {
     name : 'content',
     label: '内容-中文',
     required: true,
     type: 'richEditor' as const,
     colSpan: 24,
    },
    {
     name : 'en_content',
     label: '内容-英文',
     required: true,
     type: 'richEditor' as const,
     colSpan: 24,
    },
    {
      name:'status',
      label:"状态",
      type:'radio',
      options:[{label:'启用',value:0},{label:'禁用',value:1}],
      defaultValue:0,
      colSpan:6,
    },
   
  ];

  

  const handleSubmitClick = async (type: string, values: any, cb: () => void) => {
    try {
      if (type == 'Add') {
      } else {
      }
    } catch (err: any) {
      if (err.response.data.code == 40050) {
        message.error('邮箱错误或不存在');
        modalRef.current.setFieldError('email', '邮箱错误');
      }
      return;
    }
    cb && cb();
    fetchUserList();
    setVisible(false);
  };
  
  // 统一的 useEffect：组件挂载时和 query 变化时都会调用
  useEffect(() => {
    fetchUserList();
  }, [query]);
  useEffect(()=>{
    getArtClassListApi().then((res: any)=>{
      setArtClassList(res.results);
      const artClassData = res.results.map((item: any)=>({
        ...item,
        i18n: JSON.parse(item.i18n),
      })).map((item: any)=>({
        label: item.i18n['zh-CN'].name,
        labelEn: item.i18n['en-US']?.name,
        value: item.id
      })).filter((item: any)=>item?.labelEn!='All') || [];
      setARTCLASSMAP(artClassData);
      localStorage.setItem('BLOG_ARTCLASSMAP', JSON.stringify(artClassData));
    });
  },[])
  const handleSearch = (values: any) => {
    setQuery((pre) => ({
      ...pre,
      ...values,
    }));
  };
  const handleReset = () => {
    setQuery((pre) => ({
      page: 1,
      page_size: 10,
    }));
  };

  return (
    <>
      <Row>
        <Col>
          <SakuraSearchForm
            fields={formFields}
            onAddClick={handleAddClick}
            onSearch={handleSearch}
            onReset={handleReset}
            createField={true}
          />
        </Col>
      </Row>
      <IppeakTable
        loading={loading}
        dataSource={list}
        columns={columns}
        tableHeight={272}
        rowKey='index'
        selectedRowKeys={selectedRowKeys}
        onSelectChange={onSelectChange}
        pagination={{
          pageSize,
          total,
          current,
          showJumper: true,
          onCurrentChange(current: number, pageInfo: any) {
            setQuery((pre) => ({
              ...pre,
              page: pageInfo.current,
            }));
          },
          onPageSizeChange(size: number) {
            setQuery((pre) => ({
              ...pre,
              page_size: size,
            }));
          },
        }}
      />
      <SakuraModal
        ref={modalRef}
        visible={visible}
        title={'订单'}
        onClose={() => {
          setVisible(false);
        }}
        onSubmit={handleSubmitClick}
        type={opType}
        initialValues={opType == 'Edit' ? editingItem : initData}
        fields={fields}
      ></SakuraModal>
      
      <SakuraDrawer
        ref={drawerRef}
        visible={drawerVisible}
        onClose={handleDrawerClose}
        title="博客文章"
        type={opType}
        initialValues={editingItem}
        width="45%"
        size="large"
        placement="right"
        destroyOnClose={true}
        showCloseBtn={true}
        showConfirmBtn={true}
        confirmText="保存"
        cancelText="取消"
        onConfirm={handleDrawerSubmit}
        onCancel={handleDrawerClose}
        drawerFormFields={drawerFormFields}
        uploadApi={uploadFileApi}
      />
      <DetailDrawer visible={detailVisible} onClose={() => setDetailVisible(false)} data={detailItem} />
      
      
    </>
  );
};

const selectPage: React.FC = () => (
  <div className={classnames(CommonStyle.pageWithPadding, CommonStyle.pageWithColor)}>
    <SelectTable />
  </div>
);

export default memo(selectPage);
